<?php
declare (strict_types=1);

namespace app\index\controller;

use app\admin\model\Identity;
use app\admin\model\LinksMessage;
use app\admin\model\LinksMessageViewLog;
use app\admin\model\Location;
use app\admin\model\ResourceCollect;
use app\admin\model\UsersMember;
use app\index\model\Post as PostModel;
use app\index\model\PostComment;
use app\index\model\PostLike;
use app\index\model\UsersLoginRecordModel;
use app\index\model\UsersModel;
use app\index\model\Post;
use app\index\model\UsersCateModel;
use think\facade\Db;
use think\facade\Log;

class Index extends Base
{
    public function index()
    {
        echo 999;
        exit;
    }

    /**
     * 获取身份数据
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getIdentityInfo()
    {
        $info = Identity::field('id,name,default_icon,selected_icon')->select();
        $info = $info ? $info->toArray() : [];
        foreach ($info as $k => $v) {
            $info[$k]['default_icon'] = config('url.url') . $v['default_icon'];
            $info[$k]['selected_icon'] = config('url.url') . $v['selected_icon'];
        }
        $this->responseJson(10200, 'success', $info);
    }

    /**
     * 小程序用户授权登录
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userAuthLogin()
    {
        if (!$this->request->isPost()) {
            Log::write('请求方式有误', 'error');
            $this->responseJson(10500, '发生异常');
        }

        $post = $this->request->post();
        if (empty($post['code'])) {
            Log::write('code不存在', 'error');
            $this->responseJson(10500, '授权失败');
        }

        // 小程序appid
        $params['appid'] = config('wxapplets.appid');
        // 小程序秘钥
        $params['secret'] = config('wxapplets.appsecret');
        $params['js_code'] = $this->define_str_replace($post['code']);
        $params['grant_type'] = 'authorization_code';
        $arr = httpCurl('https://api.weixin.qq.com/sns/jscode2session', $params, 'GET');
        if (!is_array($arr)) {
            $arr = json_decode($arr, true);
        }

        // 返回状态信息，表示失败
        if (isset($arr['errcode'])) {
            $log['errcode'] = $arr['errcode'];
            $log['errmsg'] = $arr['errmsg'];
            Log::write('userAuthLogin:' . json_encode($log), 'error');
            $this->responseJson(10500, $arr['errmsg']);
        }

        if (empty($arr['session_key'])) {
            $this->responseJson(10500, 'session_key获取失败');
        }

        // https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html
        if (isset($arr['session_key']) && isset($post['encrypteData']) && isset($post['iv'])) {
            $data = $this->decryptData($params['appid'], $arr['session_key'], urldecode($post['encrypteData']), $this->define_str_replace($post['iv']));
            if (!$arr['openid']) {
                $arr['openid'] = $data['openId'];
            }
            if (!$post['nickname'] && !$arr['nickname']) {
                $post['nickname'] = $data['nickName'];
            }
            if (!$post['avatarUrl'] && !$arr['avatarUrl']) {
                $post['avatarUrl'] = $data['avatarUrl'];
            }
            if (!$post['sex'] && !$arr['sex']) {
                $post['sex'] = $data['sex'];
            }
        }

        if (!$arr['openid']) {
            Log::write('openid获取失败', 'error');
            $this->responseJson(10500, '小程序授权登录失败');
        }

        // 暂时更改，不在此做数据合并
//        $update = [];
//        if (isset($arr['unionid'])) {
//            $info = UsersModel::where('unionid', $arr['unionid'])->find();
//            $update['unionid'] = $arr['unionid'];
//        }
//
//        if (!isset($info)) {
//            $info = UsersModel::where('openid', $arr['openid'])->find();
//        }

        $info = UsersModel::where('openid', $arr['openid'])->find();

        // 不存在用户信息
//        if (!isset($info)) {
        if (empty($info)) {
            // 获取最新的用户id
            $lastId = UsersModel::order('id', 'desc')->value('id');
            $lastId++;
            // 数据
            $insertData = [
                'openid' => $arr['openid'],
                'unionid' => isset($arr['unionid']) ? $arr['unionid'] : '',
                'nickname' => isset($post['nickname']) ? emojiEncode($post['nickname']) : '游客' . $lastId,
                'sex' => isset($post['sex']) ? $post['sex'] : -1,
                'country' => isset($data['country']) ? $data['country'] : '',
                'province' => isset($data['province']) ? $data['province'] : '',
                'city' => isset($data['city']) ? $data['city'] : '',
                'headimg' => isset($post['avatarUrl']) ? $post['avatarUrl'] : 'https://yunliuns.oss-cn-shenzhen.aliyuncs.com/public/defaultHeadImgUrl/default.png',
                // 标识账号所在端
                'associate' => 2,
            ];
            $res = UsersModel::create($insertData);
            if (!$res) {
                $this->responseJson(10500, 'User Error');
            }
            $info = $insertData;
            $info['id'] = $res->id;
        }

        // token更新
        $token = md5(time() . md5($arr['openid']));
        $update['token'] = $token;
        $upres = UsersModel::update($update, ['openid' => $arr['openid']]);
        if (!$upres) {
            $this->responseJson(10500, 'Token Error');
        }
        unset($info['token'], $info['token1']);
        $info['token'] = $token;
        $this->responseJson(10200, 'success', $info);

    }

    /**
     * 更新用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateUserInfo()
    {
        $userInfo = $this->checkLogin();
        Log::write('用户:' . $userInfo['nickname'] . '修改用户信息', 'error');

        if (!$this->request->post()) {
            $this->responseJson(10500, '发生异常');
        }
        $param = $this->request->param();
        $update = [
            'sex' => isset($param['gender']) ? $param['gender'] : '',
            'nickname' => isset($param['nickname']) ? emojiEncode($param['nickname']) : '',
            'headimg' => isset($param['avatarUrl']) ? $param['avatarUrl'] : '',
            'province' => isset($param['province']) ? $param['province'] : '',
            'city' => isset($param['city']) ? $param['city'] : '',
            'country' => isset($param['country']) ? $param['country'] : '',
            'status' => 1
        ];

        $uid = UsersModel::where(['id' => $userInfo['id']])->value('id');
        if (!$uid) {
            $this->responseJson(10400, 'empty');
        }

        // 启动事务
        Db::startTrans();
        try {
            UsersModel::update($update, ['id' => $userInfo['id']]);

            $update1 = [];
            if (isset($param['cids']) && $param['cids']) {
                $update1['cids'] = $param['cids'];
            }

            if (isset($param['identity_id']) && $param['identity_id']) {
                $update1['identity_id'] = $param['identity_id'];
            }

            if (!empty($update1)) {
                $where = ['uid' => $uid];
                $find = UsersCateModel::where($where)->find();
                if (empty($find)) {
                    $update1['uid'] = $uid;
                    UsersCateModel::create($update1);
                } else {
                    UsersCateModel::update($update1, $where);
                }
            }

            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->responseJson(10500, $e->getMessage());
        }

        $this->responseJson(10200, 'success');
    }

    /**
     * 更新身份信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateIdentity()
    {
        $userInfo = $this->checkLogin();
        Log::write('用户:' . $userInfo['nickname'] . '修改用户身份', 'error');

        if (!$this->request->post()) {
            $this->responseJson(10500, '发生异常');
        }

        $param = $this->request->param();
        if (!isset($param['uid']) || !isset($param['identity_id']) || $param['identity_id'] <= 0) {
            $this->responseJson(10500, '参数错误');
        }

        $where = ['uid' => $param['uid']];
        $find = UsersCateModel::where($where)->find();
        if (empty($find)) {
            $this->responseJson(10400, 'empty');
        }

        $find1 = Identity::where('id', $param['identity_id'])->find();
        if (empty($find1)) {
            $this->responseJson(10400, '身份信息不存在');
        }

        $res = UsersCateModel::update(['identity_id' => $param['identity_id']], $where);

        if (!$res) {
            $this->responseJson(10500, 'error');
        }

        $this->responseJson(10200, 'success');

    }

    /**
     * 更新用户所选分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserCateInfo()
    {
        if (!$this->request->isPost()) {
            $this->responseJson(10500, '发生异常');
        }

        $param = $this->request->param();
        if (!isset($param['id']) || !isset($param['cids']) || !isset($param['identity_id'])) {
            $this->responseJson(10500, '参数有误');
        }

        $where = ['uid' => $param['id']];
        $find = UsersCateModel::where($where)->find();
        $data = [
            'uid' => $param['id'],
            'cids' => $param['cids'],
            'identity_id' => $param['identity_id'],
        ];
        if (empty($find)) {
            $res = UsersCateModel::create($data);
        } else {
            $res = UsersCateModel::update($data, $where);
        }

        if (!$res) {
            $this->responseJson(10500, 'error');
        }

        $this->responseJson(10200, 'success');
    }

    /**
     * 获取省/市/区
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLocation()
    {
//        $userInfo = $this->checkLogin();
//        Log::write('用户:' . $userInfo['nickname'] . '获取省市区', 'error');

        $location = Location::getProvince('location_id,name,pid');
        foreach ($location as $k1 => $v1) {
            $city = Location::getCity($v1['location_id'], 'location_id,name,pid');
            foreach ($city as $k2 => $v2) {
                $area = Location::getArea($v2['location_id'], 'location_id,name,pid');
                $city[$k2]['children'] = $area;
            }
            $location[$k1]['children'] = $city;
        }
        $this->responseJson(10200, 'success', $location);
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfo()
    {
//        $time = time();
//        $end_time = $time + 365 * 24 * 3600;
//        var_dump($time,$end_time);
        $userInfo = $this->checkLogin();
        Log::write('用户:' . json_encode($userInfo) . '获取用户信息', 'error');
        if (empty($userInfo)) {
            Log::write('获取用户信息为空:' . json_encode($userInfo), 'error');
            $this->responseJson(10502, '账号不存在');
        }

        $param = $this->request->param();
        // 1关联公众号  2关联小程序
        if (!isset($param['associate']) && !in_array($param['associate'], [1, 2])) {
            $this->responseJson(10500, '参数错误');
        }

        // 获取身份
        $identity_name = UsersCateModel::alias('u')
            ->join('admin_identity i', 'u.identity_id = i.id', 'left')
            ->where('u.uid', $userInfo['id'])
            ->value('name');
        $userInfo['identity_name'] = $identity_name ?: '游客';
        // 获取会员信息
        $member = UsersMember::where(['uid' => $userInfo['id'], 'is_show' => 1])->find();
        $userInfo['expire'] = '云Links会员暂未开通';
        $userInfo['is_member'] = 0;
        if (!empty($member)) {
            if ($member['end_time'] > 0) {
                $userInfo['expire'] = date('Y' . '年' . 'm' . '月' . 'd' . '日' . '', $member['end_time']) . '到期';
                $userInfo['is_member'] = 1;
            }
        }
        // 帖子数量
        // 0待审核 1正常 4已通过
        $post = Post::where(['uid' => $userInfo['id']])->whereIn('status', '0,1,4')->select();
        $post = $post ? $post->toArray() : [];
        $userInfo['post'] = count($post);
        // 收藏数量
        $userInfo['collect'] = ResourceCollect::where(['uid' => $userInfo['id']])->count();
        // 获赞数量
        $idArr = array_column($post, 'id');
        $userInfo['like'] = PostLike::whereIn('post_id', $idArr)->count();
        // 是否显示关联其他端
        $userInfo['is_associate'] = 0;
        if ($userInfo['status'] == 1 && $userInfo['unionid']) {
            $isExists = UsersModel::where(['unionid' => $userInfo['unionid'], 'associate' => $param['associate']])->whereRaw('id != ' . $userInfo['id'])->find();
//            var_dump($userInfo,$isExists);
            if (!empty($isExists)) {
                Log::write('获取用户信息：' . json_encode($userInfo) . '，存在其他端用户关联数据：' . json_encode($isExists), 'error');
                $userInfo['is_associate'] = 1;
            }
        }

        // 消息未查看条数，统计 云links通知、评论回复 数据
        $idArr = PostModel::where(['uid' => $userInfo['id']])->column('id');
//        var_dump($idArr);exit;
        // 评论帖子数量
        $comment = PostComment::whereIn('post_id', $idArr)->where('parent_id', 0)->whereRaw('uid != "' . $userInfo['id'] . '"')->where('is_view', 0)->count();

        // 回复帖子数量
        $idArr1 = PostComment::where(['uid' => $userInfo['id'], 'is_view' => 0])->column('id');
        $reply = 0;
        if ($idArr1) {
            $reply = PostComment::whereIn('reply_id', $idArr1)->count();
        }

        // 云links通知数量
        $whereRaw = "FIND_IN_SET(" . $userInfo['id'] . ",uids) OR uids = 0";
        $datas = LinksMessage::where('status', 1)->whereRaw($whereRaw)->select();
        $linksMessage = 0;
        if ($datas) {
            $wheres = ['uid' => $userInfo['id']];
            foreach ($datas as $kk => $vv) {
                $wheres['lmid'] = $vv['id'];
                $finds = LinksMessageViewLog::where($wheres)->find();
                if (empty($finds)) {
                    $linksMessage += 1;
                }
            }
        }

        $userInfo['not_view_limit'] = $comment + $reply + $linksMessage;

        $this->responseJson(10200, 'success', $userInfo);
    }

    /**
     * 经纬度换取地址
     */
    public function getAddress()
    {
        $param = $this->request->param();
        if (!isset($param['lat']) && !isset($param['lng'])) {
            $this->responseJson(10500, '参数错误');
        }

        // lng经度   lat纬度
        if ($param['lat'] && $param['lng']) {
            $url = 'http://api.map.baidu.com/geocoder/v2/?location=' . $param['lat'] . ',' . $param['lng'] . '&output=json&extensions_town=true&pois=1&ak=evQ9aCjQEnxBdG3RiZka7R0fhOp5N8nH';
            $address = json_decode(file_get_contents($url), true);
            $arr = $address['result']['addressComponent'];

            $addr = $arr['town'] ?: $address['result']['pois'][0]['addr'];
            if (!$addr) {
                $this->responseJson(10500, 'error');
            }

            $this->responseJson(10200, 'success', $addr);
        }

    }

    /**
     * 登录记录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserLoginRecord()
    {
        $type = $this->request->header('type');
        switch ($type) {
            case 0:
                $token = $this->request->header('token');
                $loginType = '小程序';
                $where = ['token' => $token];
                break;
            case 1:
                $token = $this->request->header('token1');
                $loginType = '公众号';
                $where = ['token1' => $token];
                break;
            default:
                $token = '';
                $loginType = '未知';
                $where = [];
        }

        if ($token) {
            $users = UsersModel::getUserInfo($where);
            if ($users) {
                Log::write('' . $loginType . '用户' . $users['nickname'] . '更新登录次数记录:' . $token, 'error');
                $res = UsersLoginRecordModel::create([
                    'uid' => $users['id'],
                ]);
                if (!$res) {
                    Log::write('登录次数写入失败', 'error');
                    $this->responseJson(10500, '登录次数写入失败');
                }
                Log::write('登录次数写入成功', 'error');
                $this->responseJson(10200, '登录次数写入成功');
            } else {
                Log::write('找不到该用户', 'error');
                $this->responseJson(10500, '找不到该用户');
            }
        } else {
            Log::write('token不存在', 'error');
            $this->responseJson(10500, 'token不存在');
        }
    }

}